<template>
    <d2-container>
        <el-form :inline="true" :model="dataSearch" ref="dataSearch">

            <el-form-item label="员工手机" prop="cellphone">
                <el-input v-model="dataSearch.cellphone" placeholder="请输入员工手机"></el-input>
            </el-form-item>

            <el-form-item label="员工姓名" prop="name">
                <el-input v-model="dataSearch.name" placeholder="请输入员工姓名"></el-input>
            </el-form-item>

            <el-form-item label="校区" prop="school" v-if='headquarter == 1'>
                <el-select
                        v-model="dataSearch.school"
                        filterable
                        placeholder="请选择校区"
                        @change="schoolSelected"
                        :disabled="disabled"
                >
                    <el-option
                            v-for="item in schoolList"
                            :key="item._id"
                            :label="item.name"
                            :value="item._id"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="部门" prop="department">
                <el-select v-model="dataSearch.department" filterable placeholder="请选择部门" :disabled="disabled">
                    <el-option
                            v-for="item in departmentList"
                            :key="item._id"
                            :label="item.name"
                            :value="item._id"
                    ></el-option>
                </el-select>

            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="formSubmit">
                    <d2-icon name="search"/>
                    查询
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button @click="formReset">
                    <d2-icon name="refresh"/>
                    重置
                </el-button>
            </el-form-item>
            
            
        </el-form>
        <div style="margin-bottom: 40px">
            <a href="#/staff-new">
                <el-button type="primary" style="float:right" icon="el-icon-plus" size="mini">新建员工</el-button>
            </a>
                <el-button type="primary" style="float:right;margin-right: 10px"  size="mini" @click='exportList'>导出列表</el-button>
                <el-button type="primary" style="float:right;margin-right: 10px"  size="mini" onclick="filefile.click()">批量导入</el-button>
                <input type="file" @change="uploadTemplate(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" style="display:none" id='filefile'></input>

                <el-button type="primary" style="float:right;margin-right: 10px"  size="mini" @click='downloadTemplate'>下载模板</el-button>
            </div>
        <el-table :data="dataList" border style="width: 100%">

            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="gender" label="性别"></el-table-column>
            <el-table-column prop="cellphone" label="手机"></el-table-column>
            <el-table-column prop="homeAddress" label="家庭住址"></el-table-column>
            <el-table-column prop="position" label="职位"></el-table-column>
            <!-- <el-table-column prop="reportTarget" label="汇报对象"></el-table-column> -->
            <el-table-column prop="entryDate" label="入职日期"></el-table-column>
            <el-table-column  label="所在学校">
                <template slot-scope='scope'>
                    <div style="white-space: pre-line;">{{scope.row.school}}</div>
                </template>
            </el-table-column>
            <el-table-column prop="department" label="所在部门"></el-table-column>
            <el-table-column prop="birthday" label="生日"></el-table-column>
            <!-- <el-table-column prop="class" label="当前负责班级"></el-table-column> -->

            <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                    <el-button @click="detailClick(scope.row)" type="text" size="small">查看详情</el-button>
                    <el-button @click="deleteClick(scope.row)" type="text" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                background
                layout="total,sizes,prev, pager, next,jumper"
                :page-size="pageSize"
                :current-page="currentPage"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handlerSizeChange"
                @next-click="handleNextPage"
                @prev-click="handlePrevClick"
        ></el-pagination>
    </d2-container>
</template>

<script>
    import request from "@/plugin/axios";
    import {mapState} from "vuex";
    import excel from "@/libs/util.excel"

    export default {
        data() {
            return {
                dataList: [],
                total: 0,
                pageSize: 10,
                currentPage: 1,
                classroom: [],
                dataSearch: {},
                schoolList: [],
                school: undefined,
                departmentList: [],
                department: undefined,
                cellphone: undefined,
                name: undefined,
                disabled: false,
                schoolLimit: undefined,
                headquarter : 0

            };
        },
        computed: {
            ...mapState('d2admin/user', ['info']),
        },
        methods: {
            formSubmit() {
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },
            formReset() {
                this.dataSearch = {}
                this.getDataList(this.dataSearch)
            },
            detailClick(e) {
                this.$router.push({path: "/staff-detail?id=" + e._id});
            },
            schoolSelected() {
                this.dataSearch.department = undefined
                this.getDepartmentList(1, 99999, this.dataSearch.school);
            },

            handleCurrentChange(currentPage) {
                this.currentPage = currentPage;
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },
            handlerSizeChange(pageSize) {
                this.pageSize = pageSize;
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },
            handleNextPage() {
                this.currentPage = this.currentPage + 1;
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },
            handlePrevClick() {
                this.currentPage = this.currentPage - 1;
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },
            deleteClick(e) {
                this.$confirm("此操作将删除该员工, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    request({
                        url: "/staff/deleteStaffOne",
                        method: "post",
                        data: {id: e._id}
                    }).then(res => {
                        if (res.code == 200) {
                            this.$message({
                                message: "删除成功"
                            });
                            this.getDataList(this.dataSearch);
                        }
                    });
                })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除"
                        });
                    });
            },
            getSchoolList(page, pageSize) {
                let data = {};
                data.page = 1
                data.pageSize = 999999
                request({
                    url: "/school/getSchoolList",
                    method: "post",
                    data
                }).then(res => {
                    this.schoolList = res.data.school;
                    // 返回数据
                });
            },
            getDepartmentList(page, pageSize, school) {
                let data = {};
                (data.page = page), (data.pageSize = pageSize), (data.school = school);
                request({
                    url: "/department/getDepartmentList",
                    method: "post",
                    data
                }).then(res => {
                    this.departmentList = res.data.department;
                    // 返回数据
                });
            },

            getDataList() {
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.dataSearch.schoolLimit = this.schoolLimit;

                if (this.department) {
                    this.dataSearch = this.department
                }
               
                if (this.headquarter != 1){
                    if (this.school) {
                        this.dataSearch.school = this.school._id
                    }
                    else{

                    }
                }
                
                if (this.cellphone) {
                    this.dataSearch.cellphone = this.cellphone
                }
                if (this.name) {
                    this.dataSearch.name = this.name
                }
                // if (this.dataSearch.school == undefined){
                    
                // }
                // this.dataSearch.school = this.school
                request({
                    url: "/staff/getStaffList",
                    method: "post",
                    data: this.dataSearch
                }).then(res => {
                    this.dataList = [];
                    this.dataList = res.data.staff;
                    this.dataList.forEach((item, index) => {
                        this.dataList[index].position = item.position == undefined ? '' : item.position.name
                        this.dataList[index].reportTarget = item.reportTarget == undefined ? '' :  item.reportTarget.map(value => value.name).join(',');
                        this.dataList[index].class = item.class == undefined ? '' : item.class.map(value => value.name).join(',');
                        this.dataList[index].school = item.school == undefined ? '' : item.school.map(value => value.name).join('\n');
                        this.dataList[index].gender = item.gender == 0 ? '男' : '女';
                        this.dataList[index].department = item.department == undefined ? '' : item.department.name;
                    });
                    this.total = res.data.total;
                    this.currentPage = res.data.currentPage;
                });
            },

        downloadTemplate(){

                excel.export( [{label:'名字',prop:'name'},{label:'性别',prop:'gender'},{label:'生日',prop:'birthday'},{label:'手机',prop:'cellphone'},{label:'地址',prop:'address'},{label:'部门',prop:'department'},{label:'职务',prop:'position'},{label:'入职日期',prop:'entryDate'}],[{name:'张三',gender:'0（0-男，1-女)',birthday:'2010.02.02(必须用“.”分隔)',cellphone:'13501234567',department:'教学组(名字必须正确，否则无法导入)',position:'教务(名字必须正确，否则无法导入)',address:'张哈路1111号',entryDate:'2010.02.02(必须用“.”分隔)'}],'员工批量导入模板')
                // this.$export.excel({
                //     columns: [{label:'名字',prop:'name'},{label:'性别',prop:'gender'},{label:'生日',prop:'birthday'},{label:'手机',prop:'cellphone'},{label:'地址',prop:'address'},{label:'部门',prop:'department'},{label:'入职日期',prop:'entryDate'}],
                //     data: [{name:'张三',gender:'0（0-男，1-女)',birthday:'2010.02.02(必须用“.”分隔)',cellphone:'13501234567',department:'教学组(名字必须正确，否则无法导入)',address:'张哈路1111号',entryDate:'2010.02.02(必须用“.”分隔)'}],
                //     title : '员工批量导入模板'
                // })
                //     .then(() => {
                //         this.$message('导出表格成功')
                //     })
            },

            exportList(){
                let school;
                let _class;
                let data = {}
                
                if(this.school.headquarter != 1 ){
                    this.dataSearch.school = this.info.school.map(value => value._id);
                    data.school = this.dataSearch.school;
                }
                

                
                data.page = 1
                data.pageSize = 999999
                const loading = this.$loading({
                    lock :true,
                    text:'',
                    spinner :'el-icon-loading',
                    background:'rgba(0, 0, 0, 0.7)'
                   })
                request({
                    url: "/staff/getStaffList",
                    method: "post",
                    data: data
                }).then(res => {
                    loading.close()
                    // if (res.code == 200){
                    //     this.$alert('','下载成功')
                    // }
                    
                    if (res.code == 200){
                        let temp = []
                    temp = res.data.staff;
                    temp.forEach((item, index) => {
                        temp[index].position = item.position == undefined ? '' : item.position.name
                        temp[index].reportTarget = item.reportTarget == undefined ? '' :  item.reportTarget.map(value => value.name).join(',');
                        temp[index].class = item.class == undefined ? '' : item.class.map(value => value.name).join(',');
                        temp[index].school = item.school == undefined ? '' : item.school.map(value => value.name).join(',');

                        temp[index].gender = item.gender == 0 ? '男' : '女';
                        temp[index].department = item.department == undefined ? '' : item.department.name;
                        // temp[index].entryDate = item.entryDate == undefined ? '' : new Date(entryDate)

                    });
                        excel.export( [{label:'姓名',prop:'name'},{label:'性别',prop:'gender'},{label:'校区',prop:'school'},{label:'手机',prop:'cellphone'},{label:'职位',prop:'position'},{label:'生日',prop:'birthday'},{label:'入职日期',prop:'entryDate'},{label:'部门',prop:'department'},{label:'地址',prop:'address'}],temp,'员工列表')

                        // this.$export.excel({
                        //     columns: [{label:'姓名',prop:'name'},{label:'性别',prop:'gender'},{label:'校区',prop:'school'},{label:'手机',prop:'cellphone'},{label:'职位',prop:'position'},{label:'生日',prop:'birthday'},{label:'入职日期',prop:'entryDate'},{label:'部门',prop:'department'},{label:'地址',prop:'address'}],
                        //     data: temp,
                        //     title : '员工列表'
                        // })
                    }
                    



                })

            },

            uploadTemplate(file){

                let thisFile = event.currentTarget.files[0]
             var rABS = false; //是否将文件读取为二进制字符串  
            const that = this
        FileReader.prototype.readAsBinaryString = function(f) {  
          var binary = "";  
          var rABS = false; //是否将文件读取为二进制字符串  
         var pt = this;  
         var workbook; //读取完成的数据  
         // var excelData;  
         var reader = new FileReader(); 
         reader.onprogress = function(e) { 
           let total = thisFile.size;
           this.progress = (e.loaded/total)*100;
           console.log( this.progress);
         };   
         reader.onload = function(e) {
            // var XLSX = require('xlsx');
           try {
             var bytes = new Uint8Array(reader.result);  
             var length = bytes.byteLength;  
             for(var i = 0; i < length; i++) {  
               binary += String.fromCharCode(bytes[i]);  
             }  
             if(rABS) {  
               workbook = XLSX.read(btoa(fixdata(binary)), { //手动转化  
                 type: 'base64'  
               });  
             }else {  
                               workbook = XLSX.read(binary, {  
                 type: 'binary'  
               });  
             } 
             // excelData = []; 
           } catch(e) {
             console.log('文件类型不正确',e);
             return;
           }
           let tempData = []
           var fromTo = '';
           for (var sheet in workbook.Sheets) {
             if (workbook.Sheets.hasOwnProperty(sheet)) {
               fromTo = workbook.Sheets[sheet]['!ref'];
               let temp = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
               for (var i = 0 ; i < temp.length ; i++){
                    let xxx = {}
                    xxx.name = temp[i]['名字']
                    xxx.cellphone = temp[i]['手机']
                    xxx.gender = temp[i]['性别']
                    xxx.birthday = temp[i]['生日']
                    xxx.entryDate = temp[i]['入职日期']
                    xxx.addrss = temp[i]['地址']
                    xxx.department = temp[i]['部门']   
                    xxx.position =    temp[i]['职务']          
                    if ((parseInt(xxx.gender) != 0) && (parseInt(xxx.gender) != 1)){
                        that.$alert('0为男，1为女','性别请填0或1')
                        return false
                    }
                    if (new Date(xxx.birthday) == 'Invalid Date'){
                                that.$alert('生日日期错误','信息错误')
                                return false
                            }
                            if (new Date(xxx.entryDate) == 'Invalid Date'){
                                that.$alert('入职日期错误','信息错误')
                                return false
                            }

                    tempData.push(xxx);
               }
               

               

             }
           }
           let data = {}
           data.data = tempData
           data.school = that.school._id
           const loading = that.$loading({
            lock :true,
            text:'',
            spinner :'el-icon-loading',
            background:'rgba(0, 0, 0, 0.7)'
           })
            request({
                    url: "/staff/importStaff",
                    method: "post",
                    data: data
                }).then(res => {
                    loading.close()
                    if (res.code == 200){
                            that.$alert('','导入成功！')
                            that.getDataList()
                        
                        
                    }
                })

         };
 
         reader.readAsArrayBuffer(f);  
 
       } 
  
       var reader = new FileReader();
       if(rABS) {  
         reader.readAsArrayBuffer(thisFile);  
       }else {  
         reader.readAsBinaryString(thisFile);  
       } 
 

            },
            load(){
                let isRoot = 2;
            this.info.role.forEach(value => {
                if (value.name === 'root') {
                    isRoot = 1
                }
            })

            if (isRoot === 2) {
                this.schoolLimit = this.info.school.map(value => value._id);
            }
            this.school = this.info.school[0]
            // if (this.school.headquarter == 1){
            //     this.headquarter = 1
            //     this.dataSearch.school = this.school._id
            // }
            this.rights = this.info.rights.map(function(e){return e.name})
            let index1 = this.rights.indexOf('root') != -1
                let index2 = this.rights.indexOf('授课老师') != -1
                let index4 = this.rights.indexOf('教务老师') != -1
                let index3 = this.rights.indexOf('教务中心') != -1
                let index5 = this.rights.indexOf('校长') != -1
                index1 = index1 || index5

            if (index1 && ((this.info.school[0].headquarter == 2) || (this.info.school[0].headquarter == 1))){

                this.headquarter = 1
                this.getSchoolList()
                // this.showSchool = true
                this.dataSearch.school = this.info.school[0]._id
            }
            else{
                this.dataSearch.school = this.info.school[0]._id
            }
            this.dataSearch.page = this.currentPage;
            this.dataSearch.pageSize = this.pageSize;
            this.getDepartmentList(1,9999,this.dataSearch.school)
            this.getDataList();
            }
        },
        beforeRouteEnter(to,from,next){
            if (to.meta.refresh == 'a'){
                to.meta.refresh = undefined
                next(v=>{
                v.load()
                })
            }
            else{
                next()
            }

        },

        created() {

            this.load()
        }
    };
</script>
